import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as CustomerEvalAction from '../../actions/customerView'
import * as Operate from '../../util/Operate'

import { WeaLeftRightLayout, WeaRightMenu,WeaTools,WeaErrorPage} from 'ecCom'

import {Button,Form,Modal,message,Table,Select} from 'antd' 
const createForm = Form.create;
const FormItem = Form.Item;
const Option = Select.Option;

import Immutable from 'immutable'
const is = Immutable.is;

let _this = null;

class CustomerEvaluation extends React.Component {
    constructor(props) {
		super(props);
        _this = this;
        this.state={
            params:{},
            dataSources:props.evalDataInfo.toJS() || []
        }
    }
    componentDidMount() {
    	const {actions,location:{query}} = this.props;
       actions.getEvaluationStandard();
       actions.getEvaluationInfo(query);

       actions.getEvalRightMenu({selectType:"evaluationinfo",...query});
    }
    componentWillReceiveProps(nextProps) {
        if(!is(this.props.evalDataInfo,nextProps.evalDataInfo)){
            this.setState({dataSources:nextProps.evalDataInfo.toJS()});
        }
    }
    shouldComponentUpdate(nextProps,nextState) {
        return  !is(this.props.customerId,nextProps.customerId)||
        !is(this.props.evalStandard,nextProps.evalStandard)||
        !is(this.state.dataSources,nextState.dataSources)||
        !is(this.state.params,nextState.params)||
        !is(this.props.evalDataInfo,nextProps.evalDataInfo)||
        !is(this.props.customereEvalRcList,nextProps.customereEvalRcList)
    }
    render() {
        const {dataSources} = this.state;
        const {evalStandard} = this.props;
        const evalStandardArr = evalStandard.toJS();
        // console.log("evalStandardArr",evalStandardArr)
        const columns = [{
            title: '名称',
            dataIndex: 'name',
            width: '30%',
        }, {
            title: '打分',
            dataIndex: 'levelId',
            render: (text, record, index) => {
                return  <div>
              {
                <Select  defaultValue={text|| evalStandardArr[0]["levelId"]}  style={{ width: '80% '}} onChange={(value)=>this.selectChange(value,index)}>
                    {this.getEvaluationOption()}
                </Select>
              }
                </div>
            },
            width: '20%',
        }, {
            title: '分值',
            dataIndex: 'levelValue',
            render: (text, record, index) => {
                return <div>{text}</div>
            },
            width: '20%',
        }, {
            title: '权重',
            dataIndex: 'proportion',
            render: (text, record, index) => {
                return <div>{text}%</div>
            },
            width: '15%',
        },{
            title: '得分',
            dataIndex: 'score',
            render: (text, record, index) => {
                return <div>{Number(record["proportion"])*Number(record["levelValue"]||1)/100}</div>
            },
            width: '15%',
        }];
        return (
            <div className="height100">
                <WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
                    <Table 
                        columns={columns} 
                        dataSource={dataSources}
                        pagination={false}
                        className="crm-customer-table"
                        footer={this.setFooter()}
                        
                    />
                </WeaRightMenu>
            </div>
        )
    }
    getRightMenu(){
        const {actions,customereEvalRcList} =this.props;
        let btns = [];
        customereEvalRcList && !is(customereEvalRcList,Immutable.fromJS([])) && customereEvalRcList.map(m=>{
            btns.push({
                icon: <i className={m.get('menuIcon')} />,
                content: m.get('menuName'),
                disabled : false
            })
        });
        // btns.push({
        //     icon: <i className='icon-coms-New-Flow'/>,
        //     content:'更新',
        //     key:0
        // });
        // btns.push({
        //     icon: <i className='icon-coms-Collection'/>,
        //     content:'收藏',
        //     key:1
        // });
    	// btns.push({
        //     icon: <i className='icon-coms-help'/>,
        //     content:'帮助',
        //     key:2
        // });
    	return btns
    }
    onRightMenuClick(key){
        const {actions,customerId,customereEvalRcList} = this.props;
        let {params } =this.state;
    //    if(key == '0'){
    //        actions.evaluationUpdate({customerId:customerId,...params});
    //    }
       let that = this;
       customereEvalRcList && !is(customereEvalRcList,Immutable.fromJS([])) && customereEvalRcList.map((m,i)=>{
           if(Number(key) == i){
               let fn = m.get('menuFun').indexOf('this') >= 0 ? `${m.get('menuFun').split('this')[0]})` : m.get('menuFun');
               if(fn == ""){
                   if(m.get('type') == "BTN_UPDATE"){ //更新
                     if(JSON.stringify(params) == "{}"){
                        const {evalStandard} = that.props;
                        const {dataSources} = that.state;
                        let _dataSource =  [].concat(dataSources);
                        const evalStandardArr = evalStandard.toJS();
                        let levelArr=[];
                        let proportionArr=[];
                        let evaluationIDArr=[];
                        for(let j=0;j<_dataSource.length;j++){
                            levelArr.push(_dataSource[j].levelId|| evalStandardArr[0].levelId);
                            proportionArr.push(_dataSource[j].proportion);
                            evaluationIDArr.push( _dataSource[j].id );
                        }
                         params={
                            level:`${levelArr}`,
                            proportion:`${proportionArr}`,
                            evaluationID:`${evaluationIDArr}`,
                        }
                     }
                        actions.evaluationUpdate({customerId:customerId,...params});
                   }
               }else{
                   fn = Operate.fnJoinPara(fn);
                   eval("Operate." + fn);
               }
           }
       });
   }
   getEvaluationOption(){
       const {evalStandard} = this.props;
        let children = [];
        evalStandard.toJS().map(item =>{
            children.push(<Option value={item.levelId} key={item.levelId}>{item.levelName}</Option>)
        })
        return children
    }
    selectChange=(value,index)=>{
       // console.log(value,index)
        const {evalStandard} = this.props;
        const {dataSources} = this.state;
        let _dataSource =  [].concat(dataSources);
        const evalStandardArr = evalStandard.toJS();
        _dataSource[index].levelId = value; 
        for(let i=0;i<evalStandardArr.length;i++){
            if(evalStandardArr[i].levelId == value){
                _dataSource[index].levelValue = evalStandardArr[i].levelValue;
            }
        }
       
        let levelArr=[];
        let proportionArr=[];
        let evaluationIDArr=[];
        for(let j=0;j<_dataSource.length;j++){
            levelArr.push(_dataSource[j].levelId|| evalStandardArr[0].levelId);
            proportionArr.push(_dataSource[j].proportion);
            evaluationIDArr.push( _dataSource[j].id );
        }
        const params={
            level:`${levelArr}`,
            proportion:`${proportionArr}`,
            evaluationID:`${evaluationIDArr}`,
        }
        this.setState({dataSources:_dataSource,params:params});
    }
    setFooter(){
        const {dataSources} = this.state;
        let sum = 0;
        for(let i=0;i<dataSources.length;i++){
            sum += Number(dataSources[i]["proportion"])*Number(dataSources[i]["levelValue"]||1)/100
        }
        return  <table><tbody ><tr>
        <td width='30%' style={{padding:"0 8px"}}></td><td width='20%' style={{padding:"0 8px"}}></td><td width='20%' style={{padding:"0 8px"}}></td>
        <td width='15%' style={{padding:"0 8px"}}>总评分: </td>
        <td width='15%' style={{padding:"0 8px"}}>{sum.toFixed(1)}</td>
        </tr></tbody></table>
    }
}

class MyErrorHandler extends React.Component {
    render(){
        const hasErrorMsg = this.props.error && this.props.error!=="";
        return (
            <WeaErrorPage msg={hasErrorMsg?this.props.error:"对不起，该页面异常，请联系管理员！"} />
        );
    }
}

CustomerEvaluation = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(CustomerEvaluation);

CustomerEvaluation = createForm({
	// onFieldsChange(props, fields) {
    //     props.actions.saveOutResourceOrderFields({...props.outResourceOrderFields.toJS(), ...fields});
    // },
	// mapPropsToFields(props) {
	// 	return props.outResourceOrderFields.toJS();
  	// }
})(CustomerEvaluation);

function mapStateToProps(state) {
    const {crmcustomerView} = state;
    return  {
        evalStandard:crmcustomerView.get('evalStandard'),
        customerId:crmcustomerView.get('customerId'),
        evalDataInfo:crmcustomerView.get('evalDataInfo'),
        customereEvalRcList:crmcustomerView.get('customereEvalRcList')
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators({...CustomerEvalAction}, dispatch)
    }
}
let Main =  connect(mapStateToProps, mapDispatchToProps)(CustomerEvaluation);
Main.Child = CustomerEvaluation;
export default Main
